<?php
/**
 * Notes:
 * 意见反馈控制器api
 * User: 大凯哥 WeChat e41613616
 * Date: 2020/3/1
 * Time: 15:02
 * ${PARAM_DOC}
 * @return ${TYPE_HINT}
 * ${THROWS_DOC}
 */

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Log;
use app\api\model\Feedback as Feed;
use app\api\model\User as UserModel;

class Feedback extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 添加反馈意见
     */
    public function add()
    {
        $param = $this->request->param();

        /*$param['nickmane'] = '大侠';
        $param['mobile'] = '18612345678';
        $param['feed_content'] = '哈哈';*/

        if (empty($param['nickmane']) || empty($param['mobile']) || empty($param['feed_content'])) {
            $this->error(__('Invalid parameters'));
        }
        $feed = new Feed();
        $param['user_id'] = $this->auth->id;
        // 父记录的意见记录id
        $param['parent_id'] = isset($param['parent_id']) ? intval($param['parent_id']) : 0;
        $param['parent_id'] <= 0 && $param['parent_id'] = 0;
        if ($param['parent_id'] > 0) {  //如果有父记录,代表的是回复
            $feedback = Feed::findInfoByCondition(['id' => $param['parent_id']]);
            if (!$feedback) {
                $this->error(__('回复的记录不存在'));
            }

            // 最顶层的意见记录id
            $param['root_id'] = intval($feedback['root_id']);
            $param['root_id'] <= 0 && $param['root_id'] = 0;
            if ($param['root_id'] <= 0) {
                $this->error(__('Invalid parameters'));
            }

            //获取该根节点的最新一条记录,判断是否可以继续回复
            $newest = Feed::findNewestRecord(['root_id' => $param['root_id']]);
            if (!$newest) {
                $this->error(__('Invalid parameters'));
            }
            if ($newest['user_id'] == $param['user_id']) {  // 用户发表的意见是最新的一条，说明后台还没有回复，请等待
                $this->error(__('请耐心等待平台后台回复！'));
            }

            //说明可以继续发送意见，去回复后台管理人员
        }
        $res = $feed->add_insert($param);
        if ($res !== 0) {
            $addRecord = Feed::findInfoByCondition(['id' => $res]);
            if ($addRecord && !$addRecord['root_id']) { //新增加的是第一条反馈记录id,更新根节点为记录id
                Feed::saveData(['id' => $addRecord['id']], ['root_id' => $addRecord['id']]);
            }
            $this->success('success', $res);
        } else {
            $this->error();
        }

    }

    /**
     * 个人意见反馈列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('page_size', 10);

        $id = $this->auth->id;
        //$id = UserModel::getCurrUid($this->request->param('user_id', 0));
        // 获取该用户所有的未处理的根记录id
        $where = [
            'user_id' => $id,
            'parent_id' => 0,
            'is_close' => 0
        ];
        $result = Feed::where($where)->page($page, $pageSize)->order('id desc')->select();

        $list = [];
        if ($result) {
            foreach ($result as $rs) {
                $data = [
                    'id' => $rs['id'],
                    'root_id' => $rs['root_id'],
                    'parent_id' => $rs['parent_id'],
                    'feedback_img' => $rs['feedback_img'],
                    'nickmane' => $rs['nickmane'],
                    'mobile' => $rs['mobile'],
                    'feed_content' => $rs['feed_content'],
                    'user_id' => $rs['user_id'],
                    'time' => date('Y-m-d H:i:s', $rs['createtime'])
                ];
                //该根意见是否可以继续反馈
                $canFeedback = 0;
                $newest = Feed::findNewestRecord(['root_id' => $rs['root_id']]);
                if ($newest && $newest['user_id'] != $rs['user_id']) {  // 用户发表的意见是最新的一条，说明后台还没有回复，请等待
                    $canFeedback = 1;
                }

                //获取子意见记录
                $childs = Feed::dataChildList(['root_id' => $rs['root_id'], 'curr_uid' => $id]);

                $list[] = [
                    'data' => $data,
                    'can_feedback' => $canFeedback,
                    'childs' => [
                        'list' => $childs ? $childs : [],
                        'has_more' => count($childs) >= $pageSize ? 1 : 0
                    ]
                ];
                unset($data);
            }
        }

        $res = [
            'list' => $list ? $list : [],
            'has_more' => count($list) >= $pageSize ? 1 : 0
        ];

        $this->success('success', $res);
    }

    /**
     * 继续加载更多字列表反馈意见
     */
    public function loadChilds()
    {
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('page_size', 10);

        $param = $this->request->param();
        $rootId = isset($param['root_id']) && $param['root_id'] ? $param['root_id'] : 0;

        $list = [];

        if ($rootId > 0) {
            $list = Feed::dataChildList(['root_id' => $rootId]);
        }

        $res = [
            'list' => $list ? $list : [],
            'has_more' => count($list) >= $pageSize ? 1 : 0
        ];

        $this->success('success', $res);
    }

    /**
     * 关闭反馈意见
     */
    public function closefb()
    {
        $param = $this->request->param();
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        $feedbackId = isset($param['fd_id']) && $param['fd_id'] ? $param['fd_id'] : 0;
        if ($feedbackId <= 0 || $userId <= 0) {
            $this->error(__('参数错误！'));
        }
        $feedback = Feed::findInfoByCondition(['id' => $feedbackId]);
        if (!$feedback) {
            $this->error(__('参数错误！'));
        }
        if ($feedback['user_id'] != $userId) {
            $this->error(__('非法操作！'));
        }

        //关闭
        Feed::saveData(['id' => $feedbackId], ['is_close' => 1]);

        $this->success('success');
    }

}